/**
 * @(#)UserConvertHandler.java
 * Copyright 2012 naryou, Inc. All rights reserved.
 */
package com.dili.dd.gpi.util.spring;

import com.diligrp.manage.sdk.domain.UserTicket;
import com.diligrp.manage.sdk.session.SessionConstants;
import com.diligrp.manage.sdk.session.SessionContext;
import com.diligrp.website.util.redis.RedisUtil;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.NativeWebRequest;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 *
 */
@Component
public class OperatorConvertHandler implements CustomObjectConvertHandler {

	@Resource(name = "manageRedisUtil")
	private RedisUtil redisUtil;

	@Override
	public Class<?> getObjectType() {
		return 	UserTicket.class;
	}
	@Override
	public Object execute(MethodParameter methodParameter,
			NativeWebRequest webRequest) {

		HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
		Cookie[] cookies = request.getCookies();
		String sessionId = null;
		if(cookies != null){
			for (Cookie cookie : cookies) {
				if(SessionConstants.SESSION_ID.name().equals(cookie.getName())){
					sessionId = cookie.getValue();
					break;
				}
			}
		}

		String sessionData = redisUtil.getString(SessionConstants.SESSION_KEY_PREFIX + sessionId);
		SessionContext sessionContext = new SessionContext();
		sessionContext.loadSessionData(sessionData);
		return sessionContext.getUserTicket();
    }
}
